#!/bin/bash

# Copyright 2020 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# Clear out old results
rm ora2pg/data/output.sql

# Create new Ora2Pg data
CURR_DIR=$(pwd)
ORACLE_TYPES="TABLE VIEW"
for ORACLE_TYPE in ${ORACLE_TYPES}
do
	if [ "${ORACLE_SCHEMAS}" == "" ]
	then
		echo "Ora2PG: ${ORACLE_TYPE}_output.sql"
		docker run  \
			-it \
			-v ${CURR_DIR}/ora2pg/config:/config \
			-v ${CURR_DIR}/ora2pg/data:/data \
			ora2pg ora2pg --type ${ORACLE_TYPE} --out ${ORACLE_TYPE}_output.sql
		sed -i '/CREATE TABLE/a \\trowid bigint GENERATED BY DEFAULT AS IDENTITY,' ora2pg/data/${ORACLE_TYPE}_output.sql
		cat ora2pg/data/${ORACLE_TYPE}_output.sql >> ora2pg/data/output.sql
	else
		for ORACLE_SCHEMA in ${ORACLE_SCHEMAS}
		do
			echo "Ora2PG: ${ORACLE_SCHEMA}.${ORACLE_TYPE}_output.sql"
			docker run  \
				-it \
				-v ${CURR_DIR}/ora2pg/config:/config \
				-v ${CURR_DIR}/ora2pg/data:/data \
				ora2pg ora2pg --type ${ORACLE_TYPE} --namespace ${ORACLE_SCHEMA} \
				--out ${ORACLE_TYPE}_${ORACLE_SCHEMA}_output.sql
			sed -i '/CREATE TABLE/a \\trowid bigint GENERATED BY DEFAULT AS IDENTITY,' ora2pg/data/${ORACLE_TYPE}_${ORACLE_SCHEMA}_output.sql
			cat ora2pg/data/${ORACLE_TYPE}_${ORACLE_SCHEMA}_output.sql >> ora2pg/data/output.sql
		done
	fi
done

# If a table does not have a PK, add rowid
CREATED_TABLES=$(grep 'CREATE TABLE' ora2pg/data/output.sql | awk '{print $3;}')
for CREATED_TABLE in ${CREATED_TABLES}
do
	PK=$(grep "ALTER TABLE ${CREATED_TABLE} ADD PRIMARY KEY" ora2pg/data/output.sql)
	if [ "${PK}" == "" ]
	then
		echo "ALTER TABLE ${CREATED_TABLE} ADD PRIMARY KEY (rowid);" >> ora2pg/data/output.sql
	fi
done
